﻿using Arch.Core;
using Meow.Core.Graphics;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;

namespace Meow.Core.Simulation;

public class UpdateRenderableBoundingSys : ECS_System , IRenderSystem
{

    QueryDescription renderableQuery = new QueryDescription()
                                    .WithAll<C_Renderable, C_Position, C_Scale, C_Rotation>();

    public UpdateRenderableBoundingSys(World world, Scene scene) : base(world, scene)
    {
    }

    void IRenderSystem.Render(GraphicsDeviceManager gdm, GameTime gameTime, float totalElapsedTime, int tick)
    {
        //world.Query(in renderableQuery, (ref C_Renderable renderable, ref C_Position pos, ref C_Rotation rot, ref C_Scale scale) =>
        //{
        //    renderable.BoundingSphere = XnaMathExts.TranslateBoundingSphere(renderable.LocalBoundingSphere, NumericsExts.Create(pos.Value, rot.Value, scale.Value));
        //});

        UpdateBounding updateBounding = new UpdateBounding();
        world.InlineParallelQuery<UpdateBounding, C_Renderable, C_Position, C_Rotation, C_Scale>(in renderableQuery, ref updateBounding);
    }

    struct UpdateBounding : IForEach<C_Renderable, C_Position, C_Rotation, C_Scale>
    {

        //
        //void IChunkJob.Execute(int index, ref Chunk chunk)
        //{
        //    chunk.GetSpan<C_Renderable, C_Position, C_Rotation, C_Scale>(
        //        out var rb, out var poses, out var rots, out var scales);

        //    foreach (var ent in chunk.Entities)
        //    {
        //        rb[ent.Id].BoundingSphere = XnaMathExts.TranslateBoundingSphere(renderable.LocalBoundingSphere, NumericsExts.Create(pos.Value, rot.Value, scale.Value));
        //    }
        //}

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void IForEach<C_Renderable, C_Position, C_Rotation, C_Scale>.Update(ref C_Renderable renderable, ref C_Position pos, ref C_Rotation rot, ref C_Scale scale)
        {
            renderable.BoundingSphere = XnaMathExts.TranslateBoundingSphere(renderable.LocalBoundingSphere, NumericsExts.Create(pos.Value, rot.Value, scale.Value));
        }

    }


}
